<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Orders extends User_Controller {

	public function __construct()
    {
        parent::__construct();
        // Your own constructor code
        $this->smarty->assign("current_class", $this->router->fetch_class());
        $this->smarty->assign("current_method",$this->router->fetch_method());
		$this->uid = $this->user_data['id'];
		if( $this->logged_in==0) {header("Location:/");exit;}
    }

    /**
     * 网课订单
     * @return [type] [description]
     */
	public function index($status = -1, $order_num = 0, $begin_time = 0, $end_time = 0,  $limit = 0)
	{
		$post_data = $this->input->post();
        if($post_data){
            $status = !empty($post_data['status']) ? $post_data['status'] : -1;
            $order_num = !empty($post_data['order_num']) ? $post_data['order_num'] : 0;
            $begin_time = !empty($post_data['begin_time']) ? $post_data['begin_time'] : 0;
            $end_time = !empty($post_data['end_time']) ? $post_data['end_time'] : 0;
        }

		//订单状态-1取消0待支付1已支付2已发货3已收货
		// $total_count = $this->User_center_model->get_order_count_by_status($this->user_data['id']);
		// $finish_count = $this->User_center_model->get_order_count_by_status($this->user_data['id'],3);
		// $cancel_count = $this->User_center_model->get_order_count_by_status($this->user_data['id'],0);
        $data = array(
            'status' => $status,
            'order_type' => 1,
            'begin_time' => $begin_time,
            'end_time' => $end_time,
            'order_num' => $order_num,
            'search_type' => 1,
         );
        //获取网课订单
        $this->load->model('User_center_model');
		$result = $this->User_center_model->get_order_list_by_uid($limit,$this->offset,$this->user_data['id'],$data);
		$this->smarty->assign("order", $result['result']);
		//分页
		$this->load->library('pagination');
		$page_config['base_url'] = '/user/orders/index/'.$status.'/'.$order_num.'/'.$begin_time.'/'.$end_time;
		$page_config['total_rows'] = $result['total_count'];
		$page_config['per_page'] = $this->offset;
        $page_config['uri_segment'] = 8;
		$this->pagination->initialize($page_config);
		$pagination = $this->pagination->create_links();
		// $this->smarty->assign("finish_count", $finish_count);
		// $this->smarty->assign("cancel_count", $cancel_count);
		$this->smarty->assign("pagination", $pagination);
        $this->smarty->assign("data", $data);
		$this->smarty->assign("menu", "orders");
		$this->smarty->display("user/order.html");
	}




	/**
     * 根据商户自定义系统订单号查询微信支付系统订单
     * @return json
     */
    public function wx_query_order()
    {
        $order_no = trim($this->input->post('order_no', true));

        require_once '/third_party/wxpayApi/wxpay.php';
        $this->config->load('wxpay', true);
        $wx_config  = $this->config->item('wxpay');
        $weixin_pay = new wxpay($wx_config);

        $response = $weixin_pay->orderQuery('', $order_no);

        $result = array('status' => -1, 'msg_code' => '', 'msg_des' => '', 'order' => '');
        if ($response['return_code'] == 'SUCCESS') {
            if ($response['result_code'] == 'SUCCESS') {
                $result['status'] = 0;
                $result['order']  = $response;
            } else {
                $result['status']   = 2;
                $result['msg_code'] = $response["err_code"];
                $result['msg_des']  = $response["err_code_des"];
            }
        } else {
            $result['status']   = 1;
            $result['msg_code'] = '微信服务器通信错误';
            $result['msg_des']  = $response["return_msg"];
        }

        exit(json_encode($result));
    }


	/**
     * 微信扫码支付模式二
     * @return view
     */
    public function wx_pay()
    {
        $order_id = intval(trim($this->input->get('order_id', true)));
        if ($order_id <= 0) {
            show_message('/user_center/recharge.html', '没有订单ID无法支付订单！');
            exit();
        }

        $sql = "/*master*/ SELECT id, order_no,unit_price_type,qty,order_type,vid,anchor_id, order_amount, payment_type_id, add_time, source, status FROM " . $this->db->dbprefix('yb_order') . " WHERE id = {$order_id} ";

        $order_data = $this->db->query($sql)->row_array();
        if (!is_array($order_data) || empty($order_data) || !$order_data['payment_type_id'] || $order_data['source'] != 2) {
            show_message('/user_center/recharge.html', '订单无效！');
            exit();
        }

        if ($order_data['status'] == 1) {
            show_message('/user_center/recharge.html', '订单已支付！');
            exit();
        }

        if ($order_data['status'] == 2) {
            show_message('/user_center/recharge.html', '订单支付失败！');
            exit();
        }

        $current_timestamp = time();
        $order_add_time    = intval($order_data['add_time']);
        $diff_timestamp    = 900; // 支付订单 15分钟过期
        if (($current_timestamp - $order_add_time) >= $diff_timestamp) {
            show_message('/user_center/recharge.html', '订单已经失效！');
            exit();
        }

        require_once APPPATH . 'third_party/wxpayApi/wxpay.php';
        $this->config->load('wxpay', true);
        $wx_config  = $this->config->item('wxpay');
        $notify_url = $wx_config['notify_url'];
        unset($wx_config['notify_url']);
        $weixin_pay = new wxpay($wx_config);

        $payment_info             = $this->db->select('id, ratio')->where(array('id' => $order_data['payment_type_id']))->get('payment_type')->row_array();
		$order_type = intval($order_data['order_type']);
		if($order_type>0){
			$unit_price_type = intval($order_data['unit_price_type']);
			$qty = intval($order_data['qty']);
			if($unit_price_type==1){
				$use_day=1;
			}else{
				$use_day=30;
			}
			$use_total_day=$use_day*$qty;
			$order_data['order_desc'] = sprintf('%s元购买%s天课程', $order_data['order_amount'],$use_total_day);
		}else{
			$order_data['order_desc'] = sprintf('%s元购买%s学币', $order_data['order_amount'], $payment_info['ratio'] * $order_data['order_amount']);
		}
        $param['body']             = "考上了充值中心-学币充值";
        $param['attach']           = $order_data['id'];
        $param['detail']           = $order_data['order_desc'] . '，单号：' . $order_data['order_no'];
        $param['out_trade_no']     = $order_data['order_no'];
        $param['total_fee']        = $order_data['order_amount'] * 100;
        $param["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];
        $param["time_start"]       = date("YmdHis");
        $param["time_expire"]      = date("YmdHis", time() + 600);
        $param["notify_url"]       = $notify_url;
        $param["trade_type"]       = "NATIVE"; //扫码支付模式二
        $param["product_id"]       = $order_data['payment_type_id'];

        //微信同一下单接口
        $response = $weixin_pay->unifiedOrder($param);

        $result = array('status' => -1, 'msg_code' => '', 'msg_des' => '', 'code_url' => '');
        if ($response['return_code'] == 'SUCCESS') {
            if ($response['result_code'] == 'SUCCESS') {
                $result['status']   = 0;
                $result['code_url'] = $response["code_url"];

                $log_info = $this->db->select('id')->where(array('order_no' => $order_data['order_no'], 'status' => 5))->get('yb_order_log')->row_array();
                if (empty($log_info)) {
                    //记录订单操作数据库日志
                    $payment_info              = $this->db->select('id, ratio')->where(array('identifier' => 'weixinpay'))->get('payment_type')->row_array();
                    $order_log['payment_id']   = isset($payment_info['id']) ? $payment_info['id'] : 0;
                    $order_log['order_no']     = $order_data['order_no'];
                    $order_log['order_detail'] = json_encode($order_data);
                    $order_log['status']       = 5; //5、等待付款
                    $order_log['add_time']     = time();
                    $this->add_order_log($order_log);
                }

            } else {
                $result['status']   = 2;
                $result['msg_code'] = $response["err_code"];
                $result['msg_des']  = $response["err_code_des"];
            }
        } else {
            $result['status']   = 1;
            $result['msg_code'] = '微信服务器通信错误';
            $result['msg_des']  = $response["return_msg"];
        }

        $this->seo['seo_title'] = "学币充值";
        $this->ci_smarty->assign("seo", $this->seo);
        $this->ci_smarty->assign("result", $result);
        $this->ci_smarty->assign("order_data", $order_data);
        $this->ci_smarty->display("user_center/weixinpay.html");
    }


		function comment($order_id){
            $this->smarty->assign("order_id", $order_id);
			$this->smarty->display("user/order_comment.html");
		}

		function comment_ajax(){
			$post_data = $this->input->post();

            if(empty($this->user_data['id'])){
                echo json_encode(array("error" => 1, "msg" => "请先登录"));
                exit;
            }

			if(empty($post_data['socre'])){
                echo json_encode(array("error" => 1, "msg" => "请选择评分"));
                exit;
            }

            if(empty($post_data['comment'])){
                echo json_encode(array("error" => 1, "msg" => "请输入评价内容"));
                exit;
            }

            if(empty($post_data['order_id'])){
                echo json_encode(array("error" => 1, "msg" => "缺少订单号"));
                exit;
            }
            $order_info = get_field_by_where("shopping_orders", "*", "order_id='{$post_data['order_id']}'");
            if(!$order_info){
                echo json_encode(array("error" => 1, "msg" => "您评价的订单不存在"));
                exit; 
            }
            if($order_info['comment_status'] == 1){
                echo json_encode(array("error" => 1, "msg" => "该订单评价过了，不能重复评价"));
                exit; 
            }
            if($order_info['buyer_user_id'] != $this->user_data['id']){
                echo json_encode(array("error" => 1, "msg" => "不能评价别人的订单"));
                exit; 
            }
            $products = json_decode($order_info['order_products'], true);
            $comment_data['uid']        = $this->user_data['id'];
            $comment_data['top_id']     = $products[0]['course_id'];
            $comment_data['type']       = $order_info['order_type'];
            $comment_data['content']    = $post_data['comment'];
            $comment_data['star']       = $post_data['socre'];
            $comment_data['ip']         = getip();
            $comment_data['add_time']   = time();
            $insert_id = 0;
            if(in_array($order_info['order_type'], array(1,2,3))){
                $this->db->insert("course_comment", $comment_data);
                $insert_id = $this->db->insert_id();
                $this->db->where(array('id'=>$products[0]['course_id']));
                $this->db->set('comment_count','comment_count + 1',FALSE);
                $this->db->set('star'.$post_data['socre'], 'star'.$post_data['socre'].' + 1',FALSE);
                $this->db->update('course');
            }else if($order_info['order_type'] == 4){
                $this->db->insert("tiku_comment", $comment_data);
                $insert_id = $this->db->insert_id();
            }else if($order_info['order_type'] == 5){
                $this->db->insert("shixun_comment", $comment_data);
                $insert_id = $this->db->insert_id();
            }
            if($insert_id > 0){
                $this->db->where("order_id", $post_data['order_id']);
                $this->db->update("shopping_orders", array("comment_status" => 1));
                echo json_encode(array("error" => 0, "msg" => "评价成功"));
            }else{
                echo json_encode(array("error" => 2, "msg" => "评价失败，请重试"));
            }
		}

    function del($order_id){
        $order_info = get_field_by_where("shopping_orders", "*", "order_id = '{$order_id}'");
        if(!$order_info){
            show_message($_SERVER['HTTP_REFERER'], "订单不存在");exit;
        }
        if($order_info['buyer_user_id'] != $this->user_data['id']){
            show_message($_SERVER['HTTP_REFERER'], "该订单不是你的，无法删除");exit;
        }
        if($order_info['order_status'] > 0){
            show_message($_SERVER['HTTP_REFERER'], "该订单已付款，无法删除");exit;
        }
        $this->db->where("order_id", $order_id);
        $this->db->delete("shopping_orders");
        if($this->db->affected_rows() > 0){
            show_message($_SERVER['HTTP_REFERER'], "订单删除成功");exit;
        }else{
            show_message($_SERVER['HTTP_REFERER'], "订单删除失败，请重试");exit;
        }
    }
}
